package com.xinchao.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xinchao.core.BaseController;
import com.xinchao.core.constant.BusinessConstant;
import com.xinchao.core.constant.RequestConstant;
import com.xinchao.core.constant.ResponseConstant;
import com.xinchao.core.exception.ControllerException;
import com.xinchao.core.util.HttpUtils;
import com.xinchao.model.DeviceUpgrade;
import com.xinchao.model.User;
import com.xinchao.model.dto.AreaDistrictDTO;
import com.xinchao.model.dto.DeviceModelDTO;
import com.xinchao.model.page.PageInfo;
import com.xinchao.model.sys.JsonResponse;
import com.xinchao.model.vo.DeviceModelSelectListVO;
import com.xinchao.model.vo.DeviceUpgradeListVO;
import com.xinchao.model.vo.DeviceUpgradeVO;
import com.xinchao.model.vo.UpgradeDeviceListVO;
import com.xinchao.service.AreaService;
import com.xinchao.service.DeviceInfoService;
import com.xinchao.service.DeviceModelService;
import com.xinchao.service.UpgradeService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * <p>Title: FirmwareUpgradeController</p>  
 * <p>Description: 固件升级</p>  
 * @author huangf 
 * @date 2018年7月16日
 */
@Controller
@RequestMapping(value = "/firmware")
public class FirmwareUpgradeController extends BaseController{
	private static Logger logger = LoggerFactory.getLogger(FirmwareUpgradeController.class);
	@Autowired
	private UpgradeService deviceUpgradeService;
	@Autowired
	private DeviceModelService deviceModelService;
	@Autowired
	private DeviceInfoService deviceInfoService;
	@Autowired
	private AreaService areaService;
	/**
	 * 跳转至新增固件界面
	 * @return
	 */
	@RequestMapping(value = "/goAddFirmware")
	public String goAddFirm(Model model){
		List<DeviceModelSelectListVO> deviceModelList = deviceModelService.selectList();
		model.addAttribute("deviceModelList", deviceModelList);
		return "firmware_upgrade_add";
	}

	/**
	 * 保存终端升级信息
	 */
	@ResponseBody
	@RequestMapping(value = "/saveFirmware")
	public Object saveFirmware(DeviceUpgrade deviceUpgrade, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		//验证参数
		if (deviceUpgrade == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		//验证参数
		if (StringUtils.isBlank(deviceUpgrade.getUpgradeName())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "固件名称不能为空");
		}
		//验证参数
		if (StringUtils.isBlank(deviceUpgrade.getModelId())
				|| StringUtils.isBlank(deviceUpgrade.getUrl())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "机型不能为空");
		}
		//验证参数
		if (StringUtils.isBlank(deviceUpgrade.getUrl())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "固件文件不能为空");
		}
		try {
			deviceUpgrade.setUpgradeType(BusinessConstant.DEVICE_UPGRADE_TYPE_FIRMWARE);
			deviceUpgradeService.saveDeviceUpgrade(deviceUpgrade, user, HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			logger.error("FirmwareUpgradeController save 保存终端升级信息失败：" + e.getMessage());
			return new JsonResponse(ResponseConstant.CODE_FAIL,"保存终端升级信息失败");
		}
		return "";
	}

	/**
	 * 获取固件列表
	 */
	@RequestMapping(value = "/list")
	public String firmList(Model modelView, Integer pageNum, Integer pageSize) {
		try {
			PageInfo<DeviceUpgradeListVO> pageInfo = deviceUpgradeService.listDeviceUpgradeByPage(BusinessConstant.DEVICE_UPGRADE_TYPE_FIRMWARE, pageNum, pageSize);
			modelView.addAttribute("firmList", pageInfo.getList());
			modelView.addAttribute("total", pageInfo.getTotal());
			modelView.addAttribute("pageNum", pageInfo.getPageNum());
			modelView.addAttribute("pageSize", pageInfo.getPageSize());
		} catch (Exception e) {
			logger.error("FirmwareUpgradeController firmList 获取固件列表失败：" + e.getMessage());
		}
		return "firmware_upgrade_list";
	}

	/**
	 *  跳转至升级固件
	 */
	@RequestMapping(value = "/goUpgradeFirmware")
	public Object goUpgradeFirm(HttpServletRequest request, Long deviceUpgradeId, Model model) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if (deviceUpgradeId == null) {
			logger.error("FirmwareUpgradeController goUpgradeFirm 参数deviceUpgradeId为空，请联系管理员" );
		}
		try {
			//机型
			List<DeviceModelSelectListVO> deviceModelList = deviceModelService.selectList();
			model.addAttribute("deviceModelList", deviceModelList);
			DeviceUpgradeVO deviceUpgradeVO = deviceUpgradeService.getDeviceUpgradeByIdVo(deviceUpgradeId);
			model.addAttribute("deviceUpgrade", deviceUpgradeVO);
		} catch (Exception e) {
			logger.error("FirmwareUpgradeController goUpgradeFirm 升级固件：" + e.getMessage());
		}
		return "firmware_upgrade_update";
	}


	/**
	 * 升级固件
	 */
	@ResponseBody
	@RequestMapping(value = "/upgradeFirmware", method = RequestMethod.POST)
	public Object upgradeFirm(DeviceUpgrade deviceUpgrade, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		Long deviceUpgradeId = deviceUpgrade.getDeviceUpgradeId();
		if (deviceUpgradeId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "升级ID为空，请联系管理员");
		}
		try {
			deviceUpgradeService.updateDeviceUpgrade(deviceUpgrade, user,HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("FirmwareUpgradeController upgradeFirm升级固件：" + e.getMessage());
			return e;
		}
		return "";

	}
	/**
	 *  固件-终端列表信息
	 */
	@RequestMapping(value = "/firmDeviceList")
	public String firmDeviceList(Long deviceUpgradeId, String firmVer, Integer deviceStatus, String deviceModel, String district,
	                             Integer pageNum, Integer pageSize, Model modelView, HttpServletRequest request) {
		// 放入model，用户数据回显
		modelView.addAttribute("deviceUpgradeId", deviceUpgradeId);
		modelView.addAttribute("firmVer", firmVer);
		modelView.addAttribute("deviceStatus", deviceStatus);
		modelView.addAttribute("deviceModel", deviceModel);
		modelView.addAttribute("district", district);
		//登录用户信息
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		//登录用户城市编码
		String cityCode = loginUser.getCityCode();
		String cityName = loginUser.getCityName();
		List<AreaDistrictDTO> districtList = areaService.listDistrictByCityCode(cityCode);
		modelView.addAttribute("districtList", districtList);

		// 固件版本号
		List<String> versionNameList = deviceInfoService.listAllFirmwareVersion();
		//如果versionName有空格，用“_”替换空格，因为在thymeleaf中，不支持<th:selected>不支持空格选中
		Map<String, String> versionNameMap = new HashMap<>();
		for (String versionName : versionNameList) {
			String key = versionName.replaceAll(" ", "_");
			versionNameMap.put(key, versionName);
		}
		modelView.addAttribute("versionNameMap", versionNameMap);
		//获取versionName的原始值
		if (StringUtils.isNotBlank(firmVer)) {
			firmVer = versionNameMap.get(firmVer);
		}
		// 在线状态
		Map<Object, Object> deviceStatusMap = Maps.newHashMap();
		deviceStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_ON_LINE, "在线");
		deviceStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE, "离线");
		modelView.addAttribute("deviceStatusMap", deviceStatusMap);
		
		// 机型
		List<DeviceModelDTO> deviceModelList = deviceModelService.listDeviceModelsSelectedUpgrade(deviceUpgradeId);
		modelView.addAttribute("deviceModelList", deviceModelList);

		// 固件-终端信息
		PageInfo<UpgradeDeviceListVO> pageInfo = deviceInfoService.listUpgradeDeviceByPage(cityName, null,firmVer, deviceStatus, BusinessConstant.DEVICE_UPGRADE_TYPE_FIRMWARE, deviceModel, district, pageNum, pageSize);
		modelView.addAttribute("firmDeviceList", pageInfo.getList());
		modelView.addAttribute("total", pageInfo.getTotal());
		modelView.addAttribute("pageNum", pageInfo.getPageNum());
		modelView.addAttribute("pageSize", pageInfo.getPageSize());
		
		// 汇总在线、离线终端总数 
		Long onlineCount = 0L;
		Long offlineCount = 0L;
		if ( null == deviceStatus ) {
			onlineCount = deviceInfoService.getDeviceCountByCondition(cityCode, BusinessConstant.DEVICE_INFO_STATUS_ON_LINE, null, firmVer, deviceModel,
					null, null, null, null, null, district, null);
			offlineCount = deviceInfoService.getDeviceCountByCondition(cityCode, BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE, null, firmVer, deviceModel,
					null, null, null, null, null, district, null);
		}else {
			// 查询条件筛选为在线终端，则在线终端数=所有终端数
			onlineCount = deviceStatus == BusinessConstant.DEVICE_INFO_STATUS_ON_LINE ? pageInfo.getTotal() : 0L;
			// 查询条件为离线终端，则离线终端数=所有终端数
			offlineCount = deviceStatus == BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE ? pageInfo.getTotal() : 0L;
		}
		modelView.addAttribute("onlineCount", onlineCount);
		modelView.addAttribute("offlineCount",offlineCount);
		return "firmware_upgrade_device_list";
	}

	/**
	 * 更新固件
	 */
	@ResponseBody
	@RequestMapping(value = "/updateFirmware")
	public Object updateFirm(String deviceCodes, Long deviceUpgradeId, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if (StringUtils.isBlank(deviceCodes)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"请选择终端");
		}
		if (deviceUpgradeId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"升级ID为空，请联系管理员");
		}
		try {
			deviceUpgradeService.deviceUpgrade(BusinessConstant.DEVICE_UPGRADE_TYPE_FIRMWARE,deviceCodes, deviceUpgradeId, user,HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("FirmwareUpgradeController updateFirm 更新固件失败：" + e.getMessage());
			return new JsonResponse(ResponseConstant.CODE_FAIL,"更新固件失败");
		}
		return "";
	}
	
	/**
	 * 固件文件上传
	 */
	@ResponseBody
	@RequestMapping(value = "/upload/firmware", method = RequestMethod.POST)
	public Object uploadFile(@RequestParam("files") MultipartFile files) {
		if (files == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "上传文件不能为空");
		} else if (files.getSize() <= 0) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "文件内容不能为空");
		}
		String fileName = files.getOriginalFilename();
		if (StringUtils.isBlank(fileName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空");
		}
		if (!fileName.endsWith(BusinessConstant.FILE_SUFFIX_ZIP)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "文件格式不对！");
		}
		try {
			List<Map<Object,Object>> msgList = Lists.newArrayList();
			Map<Object, Object> msgMap = deviceUpgradeService.saveFirmwareFile(files);
			msgList.add(msgMap);
			return msgList;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("FirmwareUpgradeController uploadFile 固件上传文件失败：" + e.getMessage());
			return new ControllerException("固件上传文件失败");
		}
	}

	/**
	 * 删除升级记录，（如果该条记录未被终端升级设置关联的话）
	 * @param upgradeId 升级记录的主键id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/del", method = RequestMethod.POST)
	public Object delUpgradeRecord(Integer upgradeId) {
		if ( upgradeId == null ) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "请选择要删除的数据");
		}
		return deviceUpgradeService.del(null,upgradeId);
	}
}
